package org.bear.array;

import java.util.ArrayList;
import java.util.List;

/*
    438.找到字符串中所有字母异位词
 */
public class FindAnagrams {
    public List<Integer> findAnagrams(String s, String p) {
        if (s.length()<p.length()) {
            return new ArrayList<>();
        }
        int[] target = new int[26];
        int[] current = new int[26];
        for (int i = 0; i < p.length(); i++) {
            target[p.charAt(i) - 'a']++;
            current[s.charAt(i) - 'a']++;
        }
        List<Integer> list = new ArrayList<>();
        if (equals(target, current)) {
            list.add(0);
        }
        for (int i = p.length(); i < s.length(); i++) {
            current[s.charAt(i) - 'a']++;
            current[s.charAt(i-p.length()) - 'a']--;
            if (equals(target, current)) {
                list.add(i-p.length()+1);
            }
        }
        return list;
    }

    private boolean equals(int[] target, int[] current) {
        for (int i = 0; i < 26; i++) {
            if (target[i] != current[i]) {
                return false;
            }
        }
        return true;
    }
}
